package junmo.s3caesar.mandu.nhkradionews.service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

public class NewsPlayerService extends Service implements OnCompletionListener {
	
	private static final String CLASSTAG = NewsPlayerService.class.getSimpleName();
	
	public static final int PROGRESS_START = 0;

	private MediaPlayer mediaPlayer;
	private int playbackPosition = PROGRESS_START;
	
	private final INewsPlayerService.Stub binder = new INewsPlayerService.Stub() {
		
		@Override
		public int init(String source) throws RemoteException {
			Log.v(CLASSTAG, "init()");
			
			try {
				mediaPlayer.setDataSource(source);
				mediaPlayer.prepare();
			} catch (Exception e) {
				e.printStackTrace();
				return 0;
			}

			return mediaPlayer.getDuration();
		}

		@Override
		public void start() throws RemoteException {
			mediaPlayer.start();
		}

		@Override
		public void pause() throws RemoteException {
			mediaPlayer.pause();			
			playbackPosition = mediaPlayer.getCurrentPosition();
		}

		@Override
		public void restart() throws RemoteException {
			mediaPlayer.start();
			mediaPlayer.seekTo(playbackPosition);
		}

		@Override
		public void stop() throws RemoteException {
			mediaPlayerStop();
		}

		@Override
		public int getCurrentPosition() throws RemoteException {
			return mediaPlayer.getCurrentPosition();
		}

		@Override
		public boolean isPlaying() throws RemoteException {
			return mediaPlayer.isPlaying();
		}

		@Override
		public void seekTo(int progress) throws RemoteException {
			mediaPlayer.seekTo(progress);
		}
	};
	
	@Override
	public IBinder onBind(Intent intent) {
		Log.v(CLASSTAG, "onBind()");
		init4mediaPlayer();
		return this.binder;
	}
	
	private void init4mediaPlayer() {
		mediaPlayer = new MediaPlayer();
		mediaPlayer.setOnCompletionListener(this);
	}
	
	@Override
	public boolean onUnbind(Intent intent) {
		Log.v(CLASSTAG, "onUnbind()");
		mediaPlayer.release();
		return super.onUnbind(intent);
	}
	
	@Override
	public void onDestroy() {
		Log.v(CLASSTAG, "onDestroy()");
		if(mediaPlayer != null) {
			mediaPlayer.release();
		}
		super.onDestroy();
	}

	@Override
	public void onCompletion(MediaPlayer mp) {
		mediaPlayerStop();
	}
	
	private void mediaPlayerStop() {
		mediaPlayer.stop();
		try {
			mediaPlayer.prepare();
		} catch (Exception e) {
			e.printStackTrace();
		}
		playbackPosition = PROGRESS_START;
		mediaPlayer.seekTo(PROGRESS_START);
		
		// TODO broadcast
	}
	
}
